
// -----------------------------------------------------------------------------

#include "stdafx.h"
#include "Win32.Number.h"

namespace Kif
{
namespace Win32
{

// -----------------------------------------------------------------------------
#define MaxStrLen 128

/// <summary>Copy a double to a string with given precision</summary>
/// <param name="outString"></param>
/// <param name="number">number to convert</param>
/// <param name="precision">decimal places</param>
/// <returns>a pointer to the String that contains the double as a string
/// is returned</returns>
Kif::Win32::String *Number::ToString(
   Kif::Win32::String &outString, double number,int precision)
{
   TCHAR str[MaxStrLen+1] ;
   char  outBuff[MaxStrLen+1] ;
   int   decimal, sign, olen = 0 ;

   char *buffer ;
   _TCHAR *pBuff ;

   pBuff  = str ;
   buffer = outBuff ;

   _fcvt_s((char*)buffer, MaxStrLen, number, precision, &decimal, &sign );

   int tlen = (int)strlen(buffer) ;
   if (sign) tlen++ ;
   if (decimal > 1) tlen++ ;

   if (tlen > MaxStrLen)
      throw L"<double>ToString::number is too large!";

   if (sign) {
      olen++ ;
      *pBuff = '-' ;
      pBuff++ ;
   }

   int count ;
   for (count = 0 ; count < decimal ; count++) {
      olen++ ;
      *pBuff = (_TCHAR)*buffer ;
      pBuff++ ;
      buffer++ ;
   }

   //if (!(*pOut)) {
   //   olen++ ;
   //   *pBuff = '0' ;
   //   pBuff++ ;
   //}

   olen++ ;
   *pBuff = '.' ;
   pBuff++ ;

   for (count = 0 ; count < precision ; count++) {
      olen++ ;
      *pBuff = (_TCHAR)*buffer ;
      pBuff++ ;
      buffer++ ;
   }

   *pBuff = (_TCHAR)NULL ;
   outString.Copy(str);

   return(&outString) ;
}  // end of copy double to a string...

}  // end of Kif.Win32
}  // end of Kif

